﻿#if!NETFX_CORE
using System.IO.IsolatedStorage;
#else
using Windows.Storage;
#endif
using Nx.Commands;
using Nx.UI;

namespace Nx.Modules
{
    public abstract class Setting : PropertyChangedBase, ISetting
    {
#if NETFX_CORE
        private const string ContainerName = "NxModuleSettings";
#endif
        public Setting(string key, string value, int idx)
        {
            Idx = idx;
            Key = key;

#if!NETFX_CORE
            var settings = IsolatedStorageSettings.ApplicationSettings;

            if (!settings.Contains(key))
            {
                settings.Add(key, value);
                settings.Save();
                Value = value;
            }
            else
            {
                Value = (string)settings[key];
            }
#else
            var container = GetContainer();

            if (!container.Values.ContainsKey(key))
            {
                container.Values.Add(key, value);
                Value = value;
            }
            else
            {
                Value = (string)container.Values[key];
            }
#endif

        }

        public abstract Command<object> SetCommand { get; }

        protected void Set(string value)
        {
#if!NETFX_CORE
            var settings = IsolatedStorageSettings.ApplicationSettings;
            settings[Key] = value;
            settings.Save();   
#else
            var container = GetContainer();
            container.Values[Key] = value;
#endif
            Value = value;
        }

        private string _Key;
        public string Key
        {
            get
            {
                return _Key;
            }
            private set
            {
                _Key = value;
                OnPropertyChanged(() => Key);
            }
        }

        private string _Value;
        public string Value
        {
            get
            {
                return _Value;
            }
            private set
            {
                _Value = value;
                OnPropertyChanged(() => Value);
            }
        }

        public int Idx { get; private set; }

#if NETFX_CORE
        private ApplicationDataContainer GetContainer()
        {
            var settings = ApplicationData.Current.LocalSettings;

            if (!settings.Containers.ContainsKey(ContainerName))
            {
                return settings.CreateContainer(ContainerName, ApplicationDataCreateDisposition.Always);
            }
            else
            {
                return settings.Containers[ContainerName];
            }
        }
#endif
    }
}
